package com.qcu.aop;


import com.qcu.annotation.RequireAuthorization;
import com.qcu.util.Response;
import com.qcu.util.ResponseCode;
import com.qcu.util.ThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.Map;

/**
 * @Name: MyComputer
 * @ClassName AuthorizationAspect
 * @Description:
 * @date 2025/2/17 9:31
 */
@Aspect
@Slf4j
@Component
public class AuthorizationAspect {
    @Pointcut("@annotation(com.qcu.annotation.RequireAuthorization)")
    public void pointcut(){}

    @Around("pointcut()")
    public Object around( ProceedingJoinPoint proceedingJoinPoint){
//        log.info("----------------------进入校验-------------------------------");
        Method method = ((MethodSignature) proceedingJoinPoint.getSignature()).getMethod();
        RequireAuthorization requireAuthorization = method.getAnnotation(RequireAuthorization.class);

        if (requireAuthorization == null){
            requireAuthorization = (RequireAuthorization) proceedingJoinPoint.getSignature().getDeclaringType().getAnnotation(RequireAuthorization.class);
        }
        Map<String,Object> map = ThreadLocalUtil.get();
        String role = (String) map.get("role");
        String[] roles = requireAuthorization.value();
        if (role != null && !role.equals("") && roles != null && roles.length > 0){
            try {
                for (String s : roles) {
                    if (role.equals(s)){
//                        log.info("{}认证成功",role);
                        return proceedingJoinPoint.proceed();
                    }
                }
            }catch (Throwable e) {
                throw new RuntimeException(e.getMessage(),e);
            }
        }
//        log.info("{}认证失败，权限不足",role);
        return Response.failure(ResponseCode.UNAUTHORIZED);
    }
}
